﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace iLangl
{
	public class AlertDesirializeContext : BaseResponseContext
	{
		protected ISerializedAlert serializedAlert = null;
		public override void SetContext(object context)
		{
			base.SetContext(context);

			if (document == null)
				return;

			serializedAlert = Facade.Instance.AlertManager.CreateSerializedAlert();

			XmlNode alertNode = document.SelectSingleNode("//Alert");

			if (alertNode == null)
				return;

			if (alertNode.Attributes["id"] != null)
				serializedAlert.Id = alertNode.Attributes["id"].Value;
			if (alertNode.Attributes["severity"] != null)
				serializedAlert.Severity = (eSeverity)Enum.Parse(typeof(eSeverity), alertNode.Attributes["severity"].Value);
			if (alertNode.Attributes["source"] != null)
				serializedAlert.Source = alertNode.Attributes["source"].Value;
			if (alertNode.Attributes["id"] != null)
				serializedAlert.Created = DateTime.ParseExact(
					alertNode.Attributes["created"].Value,
					DefaultSettingsManager.DateTimeFormat,
					null);

			XmlNode contentNode = alertNode.SelectSingleNode("//Content");

			if (contentNode != null)
			{
				XmlNode childNode = contentNode.ChildNodes[0];
				if (childNode is XmlCDataSection)
				{
					XmlCDataSection cdataSection = childNode as XmlCDataSection;
					serializedAlert.Content = cdataSection.Value;
				}
			}

			XmlNode packagesNode = alertNode.SelectSingleNode("//Packages");

			if(packagesNode != null)
				serializedAlert.PackageIds = packagesNode.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
		}

		public override object GetContext()
		{
			return serializedAlert;
		}
	}
}
